package crm.base.util;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;

import crm.system.entity.Agent;

public class SpringSecurityUtils {

	/**
	 * 获取当前登录用户
	 * 
	 * @return
	 */
	public static Agent getCurrentUser() {
		Authentication authentication = getAuthentication();
		if (authentication != null) {
			
			Object principal = authentication.getPrincipal();
			if (principal != null) {
				if (principal instanceof User) {
					User user = (User) principal;

					Agent agent = new Agent();
					agent.setUserName(user.getUsername());
					agent.setPassword(user.getPassword());
					
					return agent;
				}
			}
		}
		return null;
	}

	/**
	 * 获取当前登录用户名
	 * 
	 * @return
	 */
	public static String getCurrentUserName() {
		Authentication authentication = getAuthentication();
		if (authentication == null || authentication.getPrincipal() == null)
			return "";
		return authentication.getName();
	}

	private static Authentication getAuthentication() {
		return SecurityContextHolder.getContext().getAuthentication();
	}

}
